package com.ohc.leetcode.二叉树;

import com.ohc.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 2022年5月2日15:03:31
 */
public class 二叉树的最小深度111 {


    /**
     * 层序遍历
     *
     * @param root
     * @return
     */
    public static int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
//        List<List<Integer>> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int length = 0;
        int depth = 1;
        while (!queue.isEmpty()) {
            int len = queue.size();
//            List<Integer> list1 = new ArrayList<>();
            // 某一层的所有结点
            while (len > 0) {
                TreeNode node = queue.poll();
//                list1.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
            depth++;
            length++;
//            list.add(list1);

        }

//        System.out.println("list = " + list);
        return length;
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode();
        TreeNode treeNode2 = new TreeNode();
        TreeNode treeNode3 = new TreeNode();
        TreeNode treeNode4 = new TreeNode();
        treeNode1.right = treeNode2;
        treeNode1.left = treeNode3;
        treeNode2.right = null;
        treeNode2.left = treeNode4;
        treeNode3.right = null;
        treeNode3.left = null;
        treeNode4.left = null;
        treeNode4.right = null;
        treeNode1.val = 1;
        treeNode2.val = 2;
        treeNode3.val = 3;
        treeNode4.val = 4;
        int i = minDepth(treeNode1);
        System.out.println("i = " + i);
    }
}
